package com.woniuxy.yygh.cmn.config;


import com.woniuxy.yygh.model.cmn.Dict;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <P> @Author: ideaAdmin
 * <P>  Class
 * <P>  从redis里面获得当前存放的数据字典
 * <P> Date: 2022/4/19:17:49
 * <P> Description:
 */
@SuppressWarnings("all")
@Component
public class DictRedisCache implements ApplicationRunner {


    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public static Map<Long, Dict> dictCache;



    @Override
    public void run(ApplicationArguments args) throws Exception {

        if (dictCache == null) {
            this.dictCache = (Map<Long, Dict>) redisTemplate.opsForValue().get("dict");

        }

    }


    /**
     * <P>Author ideaAdmin
     * <P> 根据父id 返回它的所有子类
     * <P>Date 20:47 2022/4/19
     * <P>* @param id
     * <P>* @return java.util.List<com.woniuxy.commons.entity.Dict>
     **/
    public static List<Dict> getDict(Long id) {
        if (dictCache == null) {
            throw new NullPointerException();
        }
        return dictCache.entrySet()
                .stream()
                .filter(longDictEntry -> {
                    Dict value = longDictEntry.getValue();
                    return value.getParentId().compareTo(id) == 0;
                })
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());
    }
}
